package com.zim.aliot.service.impl;

import java.util.Base64;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zim.aliot.entity.IOTMessage;
import com.zim.aliot.entity.IOTStatus;
import com.zim.aliot.service.EntranceService;
import com.zim.aliot.service.MessageService;
import com.zim.aliot.service.StatusService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class EntranceServiceImpl implements EntranceService{
    private final Base64.Decoder decoder = Base64.getDecoder();

    @Autowired
    private Gson gson;
    
    @Autowired
    private MessageService messageService;
    
    @Autowired 
    private StatusService statusService;

    public IOTMessage getMnsMessage(String message) throws JsonSyntaxException{
        return gson.fromJson(message, IOTMessage.class);
    }

    public void autoProcess(String message) throws Exception{
        IOTMessage iotMessage = getMnsMessage(message);
        if ("upload".equals(iotMessage.getMessagetype())) {
//            log.info("上传:{}",message);
            messageService.messageHandle(decoder.decode(iotMessage.getPayload()));
            
        }else if ("status".equals(iotMessage.getMessagetype())) {
//            log.info("状态:{}",message);
            IOTStatus iotStatus=gson.fromJson(new String(decoder.decode(iotMessage.getPayload())), IOTStatus.class);
            statusService.deviceInfo(iotStatus);
        }else {
            log.error("[数据分发失败]:{}",message);
        }
        
    }
}
